import React, { PureComponent } from 'react';
import {
  DownloadOutlined,
  DownOutlined,
  PlusOutlined,
  UpOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Col, Row, Button, Input, message, Divider, Badge, Radio, Modal } from 'antd';
import queryString from 'query-string';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import downloadFile from '@/utils/utils';
import styles from '@/utils/utils.less';
import Customer from '../components/Customer';
import LineWrap from '../components/LineWrap'; // td溢出折行组件
import Area from '../components/Area';
import DictCode from '../components/DictCode';
import SearchPersonEs from '../components/SearchPersonEs';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const { confirm } = Modal;
@connect(({ searchrecord, loading }) => ({
  loading: loading.models.searchrecord,
  activeKey: searchrecord.activeKey,
  pageData: searchrecord.pageData,
  status: searchrecord.status,
  formFieldsValue: searchrecord.formFieldsValue,
  expandForm: searchrecord.expandForm,
}))
@Form.create()
class SearchRecordList extends PureComponent {
  state = {
    selectedRows: [],
    selectedRowKeys: [],
    statusMap: ['', 'success', 'default'],
  };

  formItemLayout1 = {
    labelCol: {
      lg: {
        span: 7,
      },
      xl: {
        span: 6,
      },
      xxl: {
        span: 4,
      },
    },
    wrapperCol: {
      xxl: {
        span: 17,
      },
    },
  };

  tableSearchLayout = {
    labelCol: { md: { span: 7 } },
    wrapperCol: { md: { span: 17 } },
  };

  // 收缩
  toggleForm = () => {
    const { expandForm, dispatch } = this.props;
    dispatch({
      type: 'searchrecord/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  componentDidMount = () => {
    this.basciDict();
  };

  // 跳转到新增
  gosearchAdd = () => {
    router.push('/hrmanage/searchrecord/add');
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'searchrecord/updateModelData',
      payload: { formFieldsValue: {} },
    });
  };

  // 查询
  getList = (activeKey = '', currentPage = 1, pageSize = 10, queryParam, isClear = true) => {
    const { dispatch, form } = this.props;
    if (isClear) {
      this.setState({
        selectedRows: [],
        selectedRowKeys: [],
      });
    }
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const newFieldsValue = queryParam || fieldsValue;
      dispatch({
        type: 'searchrecord/updateModelData',
        payload: { activeKey, formFieldsValue: fieldsValue },
      });
      const formFieldsValue = {};
      Object.keys(newFieldsValue).forEach(key => {
        if (key === 'type') {
          formFieldsValue[key] = fieldsValue[key] && fieldsValue[key].join(',');
        } else {
          formFieldsValue[key] =
            newFieldsValue[key] === undefined ? null : newFieldsValue[key].trim();
        }
      });
      const pageArg = { currentPage, pageSize };
      const consultRcrd = {
        ...formFieldsValue,
        state: activeKey,
      };
      const values = {
        consultRcrd,
        pageArg,
      };
      dispatch({
        type: 'searchrecord/fetchList',
        payload: values,
      });
    });
  };

  // 字典
  basciDict = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'searchrecord/getDic',
      payload: ['MSGTYPE', 'CONSULT_WAY', 'CONSULT_STATUS'],
    }).then(() => {
      const {
        location,
        activeKey,
        pageData: { pagination },
      } = this.props;
      const { isMenuLink } = queryString.parse(location.search);
      const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
      dispatch({
        type: 'searchrecord/updateModelData',
        payload: {
          activeKey: tempActiveKey,
        },
      });
      if (isMenuLink) {
        this.resetAndGeLlist(location);
      } else {
        this.getList(tempActiveKey, pagination.current, pagination.pageSize);
      }
    });
  };

  // 删除
  canceldeal = () => {
    const { selectedRows } = this.state;
    const { dispatch } = this.props;
    const canceldealArr = [];
    const values = {};
    if (selectedRows) {
      selectedRows.map(item => {
        const obj = {};
        obj.rcrdId = item.rcrdId;
        obj.vno = item.vno;
        canceldealArr.push(obj);
        return true;
      });
      values.list = canceldealArr;
      confirm({
        title: '您确定要删除吗？',
        icon: <QuestionCircleOutlined />,
        okText: '删除',
        cancelText: '取消',
        onOk: () => {
          dispatch({
            type: 'searchrecord/deleteData',
            payload: {
              ...values,
            },
          });
        },
        onCancel() {},
      });
    } else {
      message.warning('请勾选具体需要删除的数据');
    }
  };

  // 导出
  outExcel = () => {
    const { selectedRowKeys } = this.state;
    const {
      pageData: {
        pagination: { total },
      },
    } = this.props;
    if (total) {
      if (selectedRowKeys.length) {
        this.setState({
          excelLoading: true,
        });
        downloadFile({ rcrdIds: selectedRowKeys }, '/esApi/consult/exportExcel', 'POST', () => {
          this.setState({
            excelLoading: false,
          });
        });
      } else {
        confirm({
          title: '温馨提示',
          content: '请选择数据，如不选择，默认导出当前条件下所有数据！',
          icon: <QuestionCircleOutlined />,
          okText: '导出',
          cancelText: '取消',
          onOk: () => {
            this.exportExcel();
          },
        });
      }
    } else {
      message.warning('温馨提示：没有数据可以导出！');
    }
  };

  exportExcel = () => {
    const { form } = this.props;
    const { selectedRowKeys } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formFieldsValue = {};
      Object.keys(fieldsValue).forEach(key => {
        if (key === 'type') {
          formFieldsValue[key] = fieldsValue[key] && fieldsValue[key].join(',');
        } else {
          formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key].trim();
        }
      });
      downloadFile(
        { ...formFieldsValue, rcrdIds: selectedRowKeys },
        '/esApi/consult/exportExcel',
        'POST'
      );
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { activeKey } = this.props;
    this.getList(activeKey, pagination.current, pagination.pageSize, false);
  };

  onBChange = e => {
    const activeKey = e.target.value;

    this.getList(activeKey);
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const { queryParam } = location;
    await this.resetSearch();
    await this.getList(location.query.activeKey, undefined, undefined, queryParam);
    const { dispatch } = this.props;
    dispatch({
      type: 'searchrecord/updateModelData',
      payload: { expandForm: Boolean(queryParam) },
    });
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      activeKey,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名" {...this.tableSearchLayout}>
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
              })(<Input placeholder="请输入姓名" maxLength={15} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证件号" {...this.tableSearchLayout}>
              {getFieldDecorator('certNo', {
                initialValue: formFieldsValue.certNo,
              })(<Input placeholder="请输入证件号" maxLength={18} />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.getList(activeKey)}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      activeKey,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名" {...this.tableSearchLayout}>
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
              })(<Input placeholder="请输入姓名" maxLength={15} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证件号" {...this.tableSearchLayout}>
              {getFieldDecorator('certNo', {
                initialValue: formFieldsValue.certNo,
              })(<Input placeholder="请输入证件号" maxLength={18} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="咨询类型：" {...this.tableSearchLayout}>
              {getFieldDecorator('type', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.type,
              })(
                <DictCode
                  dictType="MSGTYPE"
                  mode="multiple"
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="客户名称" {...this.tableSearchLayout}>
              {getFieldDecorator('custId', {
                initialValue: formFieldsValue.custId,
              })(
                <Customer
                  attr
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="执行地" {...this.tableSearchLayout}>
              {getFieldDecorator('areaId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.areaId,
              })(
                <Area
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="更新人员" {...this.tableSearchLayout}>
              {getFieldDecorator('operId', {
                initialValue: formFieldsValue.operId,
              })(
                <SearchPersonEs
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" onClick={() => this.getList(activeKey)}>
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起
              <UpOutlined />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  render() {
    const { selectedRows, selectedRowKeys, excelLoading, statusMap } = this.state;
    const { pageData, loading, activeKey } = this.props;
    const columns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '证件号',
        dataIndex: 'certNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center', width: 170 } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '电话/邮箱',
        dataIndex: 'contactPhone',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (val, record) => <span>{record.contactPhone || record.contactEmail || '--'}</span>,
      },
      {
        title: '咨询类型',
        dataIndex: 'typeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <LineWrap content={text} />,
      },
      {
        title: '回复状态',
        dataIndex: 'stateName',
        width: 100,
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (val, record) => <Badge status={statusMap[record.state]} text={record.stateName} />,
      },

      {
        title: '更新时间',
        dataIndex: 'creTime',
        width: 150,
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: val => (val ? moment(val).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '更新人员',
        dataIndex: 'operName',
        width: 150,
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: val => val || '--',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width: 150,
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a onClick={() => router.push(`/hrmanage/searchrecord/revise?rcrdId=${record.rcrdId}`)}>
              更新记录
            </a>
            <Divider type="vertical" />
            <a onClick={() => router.push(`/hrmanage/searchrecord/detail?rcrdId=${record.rcrdId}`)}>
              查看
            </a>
          </span>
        ),
      },
    ];
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tabCard}>
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              margin: '16px 0',
            }}
          >
            <div>
              <Button
                type="primary"
                className={styles.listBtn}
                onClick={this.gosearchAdd}
                style={{ marginRight: '8px' }}
              >
                <PlusOutlined style={{ fontSize: 12 }} />
                新增记录
              </Button>
              <Button
                className={styles.listBtn}
                onClick={this.canceldeal}
                style={{ marginRight: '8px' }}
              >
                删除
              </Button>
              <Button className={styles.listBtn} onClick={this.outExcel} loading={excelLoading}>
                {!excelLoading && <DownloadOutlined />}
                导出
              </Button>
            </div>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <RadioGroup onChange={this.onBChange} defaultValue={activeKey}>
                <RadioButton value="">全部</RadioButton>
                <RadioButton value="2">未完成</RadioButton>
                <RadioButton value="1">已完成</RadioButton>
              </RadioGroup>
            </div>
          </div>
          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            data={pageData}
            columns={columns}
            selectedRowKeys={selectedRowKeys}
            rowKey="rcrdId"
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}
export default SearchRecordList;